<?php

namespace App\Library\Rank;

use Illuminate\Support\Facades\Redis;

abstract class AbstractSingleRank
{
    protected static $key;

    public static function getRank($id)
    {
        return Redis::zRevRank(static::$key, $id);
    }

    public static function getScore($id)
    {
        return Redis::zScore(static::$key, $id);
    }

    public static function getList($offset, $count)
    {
        return Redis::zRevRange(static::$key, $offset, $offset + $count - 1, ['withscores' => 1]);
    }

    public static function getLength()
    {
        return Redis::zCard(static::$key);
    }

    public static function increase($id, $step = 1)
    {
        Redis::zIncrBy(static::$key, $step, $id);
    }

    public static function decrease($id, $step = 1)
    {
        Redis::zIncrBy(static::$key, -1 * $step, $id);
    }

    public static function update($id, $score)
    {
        Redis::zAdd(static::$key, $score, $id);
    }

    public static function del($id)
    {
        Redis::zRem(static::$key, $id);
    }

    public static function flush()
    {
        Redis::del(static::$key);
    }

    abstract public static function refresh();

    protected static function multi(callable $callable)
    {
        Redis::multi();

        $ret = $callable();

        Redis::exec();

        return $ret;
    }
}
